﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FloodFree.Common;

namespace FloodFree.Web.Areas.Api.Controllers
{
    public class SensorsController : BaseController
    {

        public JsonResult Index()
        {
            List<Sensor> sensors = db.Sensors.ToList();
            return Json(new { Sensors = sensors }, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /Api/Sensors/Details/5

        public JsonResult Details(string id)
        {
            try
            {
                var sensor = db.Sensors
                    .Include("City")
                    .Include("City.State")
                    .Include("Updates")
                    .Where(x => x.SensorUUID.Equals(id))
                    .First();



                return Json(new
                {
                    SensorUUID = sensor.SensorUUID,
                    Address = sensor.Address,
                    sensor.City.Name,
                    State = sensor.City.State.Name,
                    Updates = from u in sensor.Updates
                              select new
                              {
                                  Id = u.Id,
                                  Date = u.Date.ToString("dd/MM/yyyy hh:mm"),
                                  StatusType = u.StatusType,
                                  Status = u.Status
                              }

                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Error = ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }

        public ActionResult Create()
        {
            return View();
        } 

        [HttpPost]
        public JsonResult Create(Sensor sensor)
        {
            try
            {
                db.Sensors.Add(sensor);
                db.SaveChanges();
                return Json(new { Sensor = sensor });
            }
            catch(Exception ex)
            {
                return Json(new { Error = ex.Message });
            }
        }
        
       
    }
}
